import { Component, ViewContainerRef, ViewChild, ComponentFactoryResolver, OnInit } from '@angular/core';
import { NavigationEnd, NavigationError, NavigationStart, Router } from "@angular/router";
import { LocalStorageService } from "./local-storage-service";
import { CommService } from "./comm-service";
import { CompMap } from "./dynacomponent/dynamaner.component";
import { OcxhelpService } from "./ocxhelp-service";
import { MyhttpService } from "./myhttp.service";

declare var $: any;

@Component({
  selector: 'app-root',
  template: `
    <!--Metrnic提供的三个点的动画-->
    <div [class.page-spinner-bar]="hasanima">
      <div class="bounce1"></div>
      <div class="bounce2"></div>
      <div class="bounce3"></div>
    </div>
    <div class="main_out">
      <div class="">
        <router-outlet></router-outlet>
      </div>
      <!--平台中的一个控件-->
      <div id="ocxRoom1"></div>
      <div id="ocxRoom2"></div>
      <div id="ocxRoom3"></div>
      <!--helpmsg iframe遮罩层-->
      <div id="myMask"></div>
      <!--全局导出文件的容器-->
      <div id="downRoom"></div>
      <div class="globalAlert">
        <ng-container #gAlertRoom></ng-container>
      </div>
    </div>
  `,
  styles: [
    ".page-spinner-bar>div{margin: 0 5px;width: 18px;height: 18px;background: orange;border-radius: 100% !important;display: inline-block;-webkit-animation: bounceDelay 1.4s infinite ease-in-out;animation: bounceDelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode: both;animation-fill-mode: both;}",
    ".page-spinner-bar .bounce1{-webkit-animation-delay: -0.32s;animation-delay: -0.32s;}",
    ".page-spinner-bar .bounce2{-webkit-animation-delay: -0.16s;animation-delay: -0.16s;}",
    ".main_out{position: relative;padding-top: 10px}",
    '#ocxRoom1{display:none;position:absolute;}',
    '#ocxRoom2{display:none;position:absolute;}',
    '#ocxRoom3{display:none;position:absolute;}',
    '#myMask{display: none;position:absolute;left: 0px;top: 0px;z-index: 1000;background-color: grey;opacity: .1}',
    "#downRoom{display: none}",
    ".globalAlert{position: absolute;right: 20px;top: 120px;width: auto;height: auto;z-index:10051;}"
  ],
  providers: [OcxhelpService]
})

export class AppComponent implements OnInit {
  hasanima: boolean = false;


  /**
   * 湖北token转化获取平台的 相关token
   * @param {string} hbtoken
   * @param {Function} callback
   */
  getptToken(hbtoken: string, callback: Function): void {
    const url = "hubei/oauth/getToken";
    this.itservice.kwPtPost(url, {
      hubeiToken: hbtoken
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            callback(resp);
          } else {
            this.commservice.myswal("warning", url, resp, "ts", null);
          }
        } else {
          this.getptToken(hbtoken, callback);
        }
      });
    });
  }

  /**
   * 获取用户详情
   */
  getuserinfo(): void {
    const url = "hubei/user/getLoginUserInfo";
    this.itservice.kwPtPost(url, null).subscribe(resp => {
      console.log(resp);
      this.commservice.handResponse("get", url, resp, (flag, resp, flag2) => {
        if (flag) {
          if (flag2) {
            const csid = resp.departmentId; //场所id
            const csmc = resp.departmentName; //场所名称
            const userName = resp.userName; // 用户昵称
            const accountName = resp.accountName; // 账号
            const examPlanId = resp.examPlanId; // 考试计划id
            const mobile = resp.mobile; // 手机号
            const roleInfoList = resp.roleInfoList; // 角色类表 object[] {id  name code} 后续可能有多个
            let nowroleid: string = "", nowrolecode: string = "", nowrolename: string = "";
            if (roleInfoList && roleInfoList.length) {
              nowroleid = roleInfoList[0].id;
              nowrolecode = roleInfoList[0].code;
              nowrolename = roleInfoList[0].name;
            }
            const userinfostr = JSON.stringify({
              csid: csid,
              cslx: "ksgljg",
              csmc: csmc,
              account: accountName,
              roleInfoList: roleInfoList,
              nowroleid: nowroleid,
              nowrolecode: nowrolecode,
              name: encodeURIComponent(userName),
              nowrolename: encodeURIComponent(nowrolename)
            });
            const aessuserinfostr = this.commservice.aesString(userinfostr);
            this.localstorage.set("info", aessuserinfostr);
            this.localstorage.set("hksjh", examPlanId);// 考试计划id
            // 获取 流媒体ip和流媒体port
            const streap_aesc = this.localstorage.get("stream");
            if (!streap_aesc) {
              this.getstreaparams(csid, "ksgljg");
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getuserinfo();
        }
      });
    });
  }

  /**
   *获取流媒体信息
   * @param {string} csid
   * @param {string} cslx
   */
  getstreaparams(csid: string, cslx: string): void {
    let url: string;
    const reqobj: any = {};
    if (cslx === "ksgljg") {
      url = "ksyw/ksgljg/jgxxXq";
      reqobj["ksgljgid"] = csid;
    } else if (cslx === "bms") {
      url = "bms/bmsjcxxgl/cxbmsxq";
      reqobj["bmsbh"] = csid;
    } else if (cslx === "bzhkd") {
      url = "ksyw/bzhkd/kdxxXq";
      reqobj["bzhkdid"] = csid;
    }
    this.itservice.kwPtPost(url, reqobj).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            //-------------------------
            const lmtip = resp.lmtip;
            const lmtdkh = resp.lmtdkh;
            const streapobj = {
              lmtip: lmtip,
              lmtdkh: lmtdkh
            };
            const aesstr = this.commservice.aesString(JSON.stringify(streapobj));
            this.localstorage.set("stream", aesstr);
          }
        } else {
          this.getstreaparams(csid, cslx);
        }
      });
    });
  }

 


  @ViewChild("gAlertRoom", { read: ViewContainerRef }) galertRoom: ViewContainerRef;

  createGlobalAlert(): void {
    const component = this.cfr.resolveComponentFactory(CompMap['myalert']);
    const ggmsgcomp = this.galertRoom.createComponent(component);
  }

  constructor(private router: Router,
    private localstorage: LocalStorageService,
    private commservice: CommService,
    private itservice: MyhttpService,
    private cfr: ComponentFactoryResolver,
    private ocxservice: OcxhelpService) {
    this.router.events.subscribe(event => {
      //路由开始切换
      if (event instanceof NavigationStart) {
        this.hasanima = true;
        // 获取湖北平台的  cookie信息
        const cookiev = this.commservice.getcookie("Authorization");
        if (!cookiev) {
          // 没有登入系统，或者缓存清空了，内部应用，无法控制父应用行为，提示下不管. 父应用应该处理了
          this.commservice.myswal("warning", "用户信息失效", "", "ts", null);
        } else {
          this.getptToken(cookiev, (resp) => {
            const connectToken = resp.connectToken;
            const accessToken = resp.accessToken;
            this.localstorage.set("signkey", connectToken);
            this.localstorage.set("token", accessToken);
            this.commservice.setSignkey(connectToken);
            this.commservice.setToken(accessToken);
            // 用户信息
            const localuerinfo_aes = this.localstorage.get("info");
            // 2021.2.22 不在对localuerinfo_aes进行判断，每次都要请求用户信息
            // if (!localuerinfo_aes) {
            this.getuserinfo();
            // }
          });

          // 判断 本子应用的请求 头部数据是否拥有
          // const token = this.commservice.getToken();
          // if (!token) {
          //   // 服务里没有token信息：  刷新操作，或者没有登入
          //   // const url = event.url;
          //   const localtoken = this.localstorage.get("token");
          //   const localsignkey = this.localstorage.get("signkey");
          //   if (!localtoken) {
          //     // 没有登入,获取
          //     this.getptToken(cookiev, (resp) => {
          //       const connectToken = resp.connectToken;
          //       const accessToken = resp.accessToken;
          //       this.localstorage.set("signkey", connectToken);
          //       this.localstorage.set("token", accessToken);
          //       this.commservice.setSignkey(connectToken);
          //       this.commservice.setToken(accessToken);
          //       // 用户信息
          //       const localuerinfo_aes = this.localstorage.get("info");
          //       // 2021.2.22 不在对localuerinfo_aes进行判断，每次都要请求用户信息
          //       // if (!localuerinfo_aes) {
          //       this.getuserinfo();
          //       // }
          //     });
          //   } else {
          //     // 简单的刷新操作
          //     this.commservice.setToken(localtoken);
          //     this.commservice.setSignkey(localsignkey);
          //     // 用户信息
          //     const localuerinfo_aes = this.localstorage.get("info");
          //     // if (!localuerinfo_aes) {
          //     this.getuserinfo();
          //     // }
          //   }
          // }
        }
      }
      //路由切换结束
      if (event instanceof NavigationEnd) {
        //隐藏三个点
        this.hasanima = false;
        const url = event.url;
        this.commservice.log("路由切换结束--url----", url);
      
      }
      //路由切换出错
      if (event instanceof NavigationError) {
        this.hasanima = false;
        console.log('路由切换出错');
      }
    });
  }

  ngOnInit(): void {
    this.createGlobalAlert();
  }
}
